import csv
import json
import os

import xlwt
import yaml
from deprecated import deprecated
from django.conf import settings
from django.http import HttpResponse


def load_json_file(path):
    content = ''
    with open(path, 'rb') as f:
        line = f.readline()
        while line:
            content += line.decode()
            line = f.readline()
    return json.loads(content)


def dump_json_file(path, data):
    with open(path, 'wb+', encoding='utf-8') as f:
        f.write(data)


def load_yaml_file(path):
    assert os.path.isfile(path), '"{}"文件不存在'.format(path)
    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()
    return yaml.load(content, Loader=yaml.FullLoader)


def dump_yaml_file(path, data):
    with open(path, 'w+', encoding='utf-8') as f:
        yaml.dump(data, f, default_flow_style=False, encoding="utf-8", allow_unicode=True)


def write_pid(output_path, pyinstaller_mode=False):
    """
    将程序进程ID输出到pid文件, pyinstaller打包模式下输出父进程ID
    :param output_path:
    :param pyinstaller_mode:
    :return:
    """
    if pyinstaller_mode:
        pid = os.getppid()
    else:
        pid = os.getpid()
    with open(output_path, 'w') as f:
        f.write(str(pid))

    return pid


def write_data_to_wb(table_headers, table_fields, table_data):
    """
    写入表格中
    :param table_headers: 表头
    :param table_fields: 字段
    :param table_data: 数据
    :return:
    """
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('sheet')
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    for alias_index, alias in enumerate(table_headers):
        ws.write(0, alias_index, alias, font_style)
    font_style = xlwt.XFStyle()
    for field_name_index, field_name in enumerate(table_fields):
        row_num = 0
        for running in table_data:
            row_num += 1
            try:
                if field_name in ['boot_time', 'start_time', 'create_timestamp']:
                    ws.write(row_num, field_name_index, running[field_name], font_style)
                else:
                    ws.write(row_num, field_name_index, running[field_name], font_style)
            except:
                ws.write(row_num, field_name_index, '', font_style)
    return wb


def data_export(file_type, aliases, field_names, result_value):
    if file_type == 0:
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=history.xls'
        wb = write_data_to_wb(aliases, field_names, result_value)
        wb.save(response)
    else:
        response = HttpResponse(content_type='text/csv', charset='utf-8')
        response['Content-Disposition'] = 'attachment;filename=history.csv'
        csv_writer = csv.writer(response)
        csv_writer.writerow(aliases)
        for value_item in result_value:
            row_temp = []
            for field_item in field_names:
                try:
                    if field_item in ['boot_time', 'start_time', 'create_timestamp']:
                        row_temp.append(value_item[field_item])
                    else:
                        row_temp.append(value_item[field_item])
                except:
                    row_temp.append('')
            csv_writer.writerow(row_temp)
    return response


def delete_packages(package_name):
    """
    删除版本信息
    :param package_name:
    :return:
    """
    package_name_no_suffix = os.path.splitext(package_name)[0]
    suffixs = ['.rpm', '.rpm.yaml', '.tgz']
    for path in [os.path.join(settings.APP_STORE_DIR, package_name_no_suffix + suffix) for suffix in suffixs]:
        try:
            os.remove(path)
        except FileNotFoundError:
            pass
